<?php

namespace App\Http\Controllers\Admin\Exts;

use App\Http\Controllers\Controller;
use App\Qingwuit\Models\Area;
use App\Qingwuit\Models\Goods;
use App\Qingwuit\Models\GoodsBrand;
use App\Qingwuit\Models\GoodsClass;
use App\Qingwuit\Models\InviteCode;
use App\Qingwuit\Models\Invites;
use App\Qingwuit\Models\Retails;
use App\Qingwuit\Models\Store;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class StoresController extends Controller
{
    protected $modelName = 'Store';

    public function update(Request $request, $id)
    {
        try {
            $rs = $this->getService($this->modelName)->editStore($id, 'id', 'admins');
            return $this->handle($rs);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

//商铺详情
    public function goodsList(Request $request)
    {
//        dd(1);
        $goodsModel = $this->getService('Goods', true);
        $user_id = $this->getUserId('users');
        $stores_id = $request->stores_id;
        $keywords = $request->keywords;

        // 关键词
        if (isset($keywords) && !empty($keywords)) {
            $keywords = urldecode($keywords);
            $goodsModel = $goodsModel->where('goods_name', 'like', '%' . $keywords . '%');
            $ast = $goodsModel->where('store_id',$stores_id)->get();
            foreach ($ast as $key => $val){
                $val->store_name = Store::where('id',$val->store_id)->first()->store_name;
                $val->store_phone = Store::where('id',$val->store_id)->first()->store_mobile;
                $binding = Retails::where('distribution_id', $val->store_id)->where('shop_id', $user_id)->first();
                if (!$binding){
                    $val->goods_price = "***";
                }else{
                    $biliId = InviteCode::where('code',$binding->code)->first();
                    $bili = Invites::where('id',$biliId->pid)->first();
                    $val->goods_price = round($val->goods_price + $val->goods_price * $bili->percentage/100,2);
                }
            }
        }else{
            $goods = Goods::where('store_id',$stores_id)->get();
            $stores = Store::where('id',$stores_id)->first();
            $uniqueGoods = $goods->unique('class_id');
            $classIds = $uniqueGoods->pluck('class_id');
            $className = [
                ['id'   => '-1',
                    'name' => '推荐']
            ];
//        print_r($className);die;
            $classNameObject = json_decode(json_encode($className));
//        print_r($classNameObject);die;
            foreach ($classIds as $k => $v){

                $name =  DB::table('goods_classes')->where( 'id',$v)->select('id','name')->first();
//           $name = (array)$name;
                array_push($classNameObject,$name);
            }

            foreach($classNameObject as $item =>$value){

                $list = Goods::where('store_id',$stores_id)->where('class_id',$value->id)->get();
                $value->chinren = $list ;
                $nominate = Goods::where('store_id',$stores_id)->where('is_recommend',1)->get();

                if($value->id == '-1'){
                    $value->chinren = $nominate;
                }
            }
            $binding = Retails::where('distribution_id', $stores_id)->where('shop_id', $user_id)->first();
//        print_r($binding);die;
            if (!$binding){
                foreach ($classNameObject as $item =>$value){
                    foreach ($value->chinren as $k=>$v){
                        $v->goods_price = "***";

                    }
                }
            }else{

//            foreach ($classNameObject as $item =>$value){
//                foreach ($value->chinren as $k=>$v){
//                    $v->goods_price = "***";
//
//                }
//            }

            }
            $arr =  ['store_logo' => $stores->store_logo,
                'store_name' => $stores->store_name,
                'store_phone' => $stores->store_phone,
                'store_description' => $stores->store_description];
            $arrObject = json_decode(json_encode($arr));
            $ast =[
                'store'=>$arrObject,
                'goods'=>$classNameObject
            ];
        }


        return $this->success($ast);

    }

//精选
    public function concentration(Request $request)
    {
        $user_id = $this->getUserId('users');
        $class_id = $request->class_id;
        $class_cid = GoodsClass::where('pid',$class_id)->select('id')->get()->toarray();
        $keywords = $request->keywords;
        $type = $request->type;
        $sort = $request->sort;
        $baseQuery = Goods::whereIn('class_id', $class_cid)
            ->where('is_master', 1)
            ->where('goods_status', 1)
            ->where('goods_name', 'like', '%' . $keywords . '%');

        if ($sort === 'asc' || $sort === 'desc') { // 确保$sort是有效的排序方向
            switch ($type) {
                case 1:
                    $data = $baseQuery->orderBy('created_at', $sort)->get();
                    break;
                case 2:
                    $data = $baseQuery->orderBy('goods_price', $sort)->get();
                    break;
                case 3:
                    $data = $baseQuery->orderBy('goods_sale', $sort)->get();
                    break;
                default:
                    // 如果没有匹配的$type，可以设置一个默认值或抛出异常
                    $data = []; // 或者你可以根据需要处理这个情况
                    break;
            }
        } else {
            // 如果$sort不是有效的排序方向，可以设置一个默认值或抛出异常
            // 这里只是简单地返回一个空数组作为示例
            $data = [];
        }
        foreach ($data as $key => $val){
            $val->store_name = Store::where('id',$val->store_id)->value('store_name');
            $binding = Retails::where('distribution_id', $val->store_id)->where('shop_id', $user_id)->first();
            if (!$binding){
                $val->goods_price = "***";
            }else{
                $biliId = InviteCode::where('code',$binding->code)->first();
                $bili = Invites::where('id',$biliId->pid)->first();
                $val->goods_price = round($val->goods_price + $val->goods_price * $bili->percentage/100,2);
            }
            if (empty($val->store_name)){
                Goods::where('id',$val->id)->delete();
            }
            $binding = Retails::where('distribution_id', $val->store_id)->where('shop_id', $user_id)->first();
            if (!$binding){
                $val->goods_price = "***";
            }
        }
     if (!empty($data)){
         $data = $data->toArray();
//        dd($sortedDataArray);
         usort($data, function($a, $b) {
//            dd($a->goods_price);
             if ($a['goods_price'] !== '***' && $b['goods_price']  === '***') {
                 return -1; // a排在b前面
             } elseif ($a['goods_price']  === '***' && $b['goods_price']  !== '***') {
                 return 1; // b排在a前面
             } else {
                 // 如果两个价格都不是'***'，或者都是'***'，则保持原始顺序
                 return 0;
             }
         });
     }
        return $this->success($data);
    }


    public function recommend()
    {
        $user_id = $this->getUserId('users');
        $data = Goods::where('is_recommend',1)
            ->orderByRaw('RAND()')
            ->get();
//        print_r($data);die;
        foreach ($data as $key => $val){
            $name = Store::where('id',$val->store_id)->first();
//            print_r($name->store_name);die;
            if (!empty($name)){
                $val->store_name = $name->store_name;
                $binding = Retails::where('distribution_id', $val->store_id)->where('shop_id', $user_id)->first();
                if (!$binding){
                    $val->goods_price = "***";
                }else{
                    $biliId = InviteCode::where('code',$binding->code)->first();
                    $bili = Invites::where('id',$biliId->pid)->first();
                    $val->goods_price = round($val->goods_price + $val->goods_price * $bili->percentage/100,2);
                }
            }else{
                $val->store_name = '未知店铺';
                $val->goods_price = "***";
            }

        }
        return $this->success($data);
    }


    public function city()
    {
        $code = \request()->code;
        $data = Area::where('pid',$code)->get();

         return $this->success($data);
    }
}
